import { computed, ref } from "vue";
import { __defaultGoods } from "./goods.js";

export class DataMgr implements engine.DataMgr {
    public readonly Prefix = '#xiaodianbao:';
    public readonly BillPrefix = '#xiaodianbao-b:';
    
    private makeDefaultGoods(): engine.GoodInfo[] {
        console.log('use default goods');
        return __defaultGoods;
    }

    public goods: Ref<engine.GoodInfo[]> = ref([]);

    public readGoods(): void {
        this.readGoodsInternal('goods');
    }

    public useOldGoods(): void {
        this.readGoodsInternal('oldGoods');
    }

    private readGoodsInternal(key: 'goods' | 'oldGoods'): void {
        try {
            const sg: engine.GoodInfo[] = uni.getStorageSync(key);
            if (sg) {
                this.goods.value.length = 0;
                this.goods.value.push(...sg);
            }
        } catch(e) {
            console.error('read goods failed');
        }
    }

    public useDefaultGoods(): void {
        this.goods.value = this.makeDefaultGoods();
    }

    public resetGoods(): void {
        this.goods.value.length = 0;
    }

    public saveGoods(): void {
        // console.log('save goods:', this.Goods);
        try {
            const oldGoods = uni.getStorageSync('goods');
            uni.setStorage({
                key: 'oldGoods',
                data: oldGoods
            });
        } catch(e) {
            console.error('save old goods failed');
        }
        uni.setStorage({
            key: 'goods',
            data: this.goods.value
        });
    }

    public addGoods(goods: engine.GoodInfo[]): void {
        for (const g of goods) {
            const idx = this.goods.value.findIndex((v) => v.name == g.name);
            if (idx >= 0) {
                this.goods.value.splice(idx, 1);
            }
        }
        this.goods.value.push(...goods);
    }

    public bills: Ref<engine.BillInfo[]> = ref([]);

    public readBills(): void {
        try {
            const savedBills = uni.getStorageSync('bills');
            this.bills.value.push(...savedBills);
            // console.log('bills:', savedBills);
        } catch(e) {
            console.error('read bills failed');
            uni.setStorage({
                key: 'bills',
                data: this.bills.value
            })
        }
    }

    public saveBills(): void {
        // console.log('save bills:', this.bills);
        uni.setStorage({
            key: 'bills',
            data: this.bills.value
        })
    }

    public addBills(bills: engine.BillInfo[]): void {
        this.bills.value.push(...bills);
        this.bills.value.sort((a, b) => b.time - a.time);
        this.saveBills();
    }

    public totalBillAmount = computed(() => {
        let ta = 0;
        for (const b of this.bills.value) {
            ta += b.totalAmount;
        }
        return ta;
    });
}
